package com.zl.gmadmin.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zl.gmadmin.common.ApiResponse;
import com.zl.gmadmin.entity.SysRole;
import com.zl.gmadmin.payload.RoleQueryCriteria;
import com.zl.gmadmin.service.SysRoleService;
import com.zl.gmadmin.utils.LogUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

/**
 * @author zhangliang
 * @version 1.0
 * @date 2021/3/22 16:20
 */
@RestController
@RequestMapping("api/roles")
@Api(tags = "系统:角色管理")
public class SysRoleController {


    private final SysRoleService sysRoleService;

    public SysRoleController(SysRoleService sysRoleService) {
        this.sysRoleService = sysRoleService;
    }

    @GetMapping("allName")
    @ApiOperation("获取所有的角色名称")
    public ApiResponse findAllName() {
        return ApiResponse.ofSuccess(sysRoleService.findAllName());
    }


    @GetMapping
    @ApiOperation("分页获取角色信息")
    public ApiResponse selectPageVo(RoleQueryCriteria roleQueryCriteria, Page<SysRole> page) {
        Map<String, Object> map = (Map<String, Object>) sysRoleService.selectPageVo(roleQueryCriteria, page);
        return ApiResponse.ofSuccess(map);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据id获取角色")
    public ApiResponse getRole(@PathVariable("id") Long id){

        return ApiResponse.ofSuccess(sysRoleService.getByRoleId(id));
    }


    @PostMapping
    @ApiOperation(value = "添加角色信息", httpMethod = "POST", response = ApiResponse.class, notes = "保存角色信息")
    public ApiResponse addRole(@RequestBody SysRole sysRole) {
        LogUtil.debug(JSONUtil.toJsonStr(sysRole));
        sysRoleService.addRole(sysRole,sysRole.getMenus());
        return ApiResponse.ofSuccess();
    }

    @PutMapping
    @ApiOperation("更新角色信息")
    public ApiResponse updateRole(@RequestBody SysRole sysRole) {
        LogUtil.debug("更新1角色信息: "+JSONUtil.toJsonStr(sysRole));
        sysRoleService.updateRole(sysRole);
        return ApiResponse.ofSuccess();
    }

    @DeleteMapping
    @ApiOperation("删除角色信息")
    public ApiResponse deleteRoles(@RequestBody Set<Long> ids) {
        sysRoleService.delRole(ids);
        return ApiResponse.ofSuccess();
    }

    @ApiOperation("导出用户信息")
    @GetMapping("/download")
    public void download(RoleQueryCriteria criteria, HttpServletResponse response) throws IOException {

        LogUtil.debug("导出:" + JSONUtil.toJsonStr(criteria));
        sysRoleService.download(response, criteria.getIds());
    }
}
